const path = require("path")
const fs = require("fs")
const jwt = require("jsonwebtoken")
const user = require("../databases/user")

module.exports = (req,res,next)=>{
  const { token } = req.body;
  const file = req.files[0];
  jwt.verify(token, "千锋H5", (err,tokenData)=>{
    if(err){
      res.send({
        code:0,
        msg:"登录失效或未登录"
      })
    }else{
      // 改名
      const oldName = path.join(__dirname, "..", "upload", file.filename);
      const newName = oldName + "-" + file.originalname;
      fs.renameSync(oldName, newName);
      // 处理前端和数据库需要的地址
      const imgUrl = "http://localhost:3000/" + newName.split("upload")[1].slice(1)
      // 存储到数据库
      user.updateOne({uId: tokenData.uId}, {
        avatar: imgUrl
      }).then(()=>{
        res.send({
          code:1,
          msg:"上传成功",
          // 响应给前端
          data: imgUrl
        })
      })
    }
  })
}

